package com.Nuyoah.demo01.service.serviceImpl;

import cn.dev33.satoken.stp.StpUtil;
import com.Nuyoah.demo01.DTO.PostPageQry;
import com.Nuyoah.demo01.VO.UserVO;
import com.Nuyoah.demo01.common.JsonResult;
import com.Nuyoah.demo01.entity.Community;
import com.Nuyoah.demo01.entity.Post;
import com.Nuyoah.demo01.entity.User;
import com.Nuyoah.demo01.mappers.PostMapper;
import com.Nuyoah.demo01.mappers.UserMapper;
import com.Nuyoah.demo01.service.PostService;
import com.Nuyoah.demo01.service.UserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    // 根据帖子ID获取帖子信息，包括作者信息
    @Override
    public Post getPostById(Integer post_id) {
        Post post = postMapper.getPostById(post_id);
        if (post != null && post.getUserId() != null) {
            post.setUser(userMapper.getUserById(post.getUserId()));
        }
        return post;
    }

    // 获取所有帖子信息，包括作者信息
    @Override
    public List<Post> getAllPosts() {
        List<Post> posts = postMapper.getAllPosts();
        for (Post post : posts) {
            if (post.getUserId() != null) {
                post.setUser(userMapper.getUserById(post.getUserId()));
            }
        }
        return posts;
    }

    // 插入帖子信息
    @Override
    public Integer insertPost(Post post) {
        return postMapper.insertPost(post);
    }

    // 更新帖子信息
    @Override
    public Integer updatePost(Post post) {
        post.setUserId((Integer) StpUtil.getLoginId());
        return postMapper.updatePost(post);
    }

    // 删除帖子信息
    @Override
    public Integer deletePost(Integer post_id) {
        return postMapper.deletePost(post_id);
    }

    @Override
    public List<Post> selectPagePosts(PostPageQry qry) {
        PageHelper.startPage(qry.getPageNum(),qry.getPageSize());
        List<Post> Posts = postMapper.selectPagePosts(qry);
        UserVO userVO = new UserVO();
        for (Post post : Posts) {
            int userId = post.getUserId();
            UserVO user = userMapper.getUserById(userId);
            userVO.setUsername(user.getUsername());
            userVO.setUserId(userId);
            userVO.setStatus(user.getStatus());
            userVO.setEmail(user.getEmail());
            userVO.setIsAdmin(user.getIsAdmin());
            post.setUser(userVO);
        }
        return  Posts;
    }

    public JsonResult<String> likePost(Integer id) {
        Integer result = postMapper.likePost(id);
        if (result > 0) {
            return new JsonResult<>("200", "点赞成功");
        } else {
            return new JsonResult<>("1", "点赞失败");
        }
    }

}